package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.User;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: dw
 * @Date 2022/3/16 22:35
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;


    /**
     * 用户登录的方法
     *
     * @param phone       用户输入的手机号
     * @param userCode    用户输入的验证码
     * @param sessionCode 后端生成的验证码
     * @return User 返回登录的用户对象
     */
    @Override
    public User login(String phone, String userCode, String sessionCode) {
        //校验验证码
        if (!userCode.equals(sessionCode)) {
            throw new BusinessException("验证码错误");
        }
        //根据手机号查询用户对象，判断是否禁用，如果找到并没有禁用直接返回
        User user = userMapper.findByPhone(phone);
        if (user!=null) {
            if (user.getStatus()==1) {
                throw new BusinessException("您的手机号已被禁用");
            }
        } else {
            //如果找不到，完善用户数据，设置状态为0，并添加用户
            //封装手机号状态
            user = new User();
            user.setPhone(phone);
            user.setStatus(0);
            userMapper.save(user);
        }

        //返回登陆用户对象
        return user;
    }
}
